<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">
          <a-collapse-panel key="1" header="基本信息">
            <a-row :gutter="48">
              <a-col :span="8">
                <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billNo">
                  <a-input v-model="model.billNo" :max-length="36" placeholder="请输入单据编号" disabled></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
                  <j-date
                    placeholder="请选择申请时间"
                    v-model="model.createTime"
                    :show-time="true"
                    date-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                    disabled
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="employeeId">
                  <select-user-by-dep
                    :multi="false"
                    v-model="model.employeeId"
                    disabled></select-user-by-dep>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="预计到岗时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="arrivalTime">
                  <a-date-picker
                    :disabled="formDisabled"
                    placeholder="请选择预计到岗时间"
                    valueFormat="YYYY-MM-DD HH:mm:ss"
                    v-model="model.arrivalTime"
                    style="width: 100%" />
                  <!-- <j-date :disabled=formDisabled placeholder="请选择预计到岗时间" v-model="model.arrivalTime"  style="width: 100%" /> -->
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="是否外派" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isExpatriate">
                  <j-dict-select-tag :disabled="formDisabled" type="list" v-model="model.isExpatriate" dictCode="yes_or_no" placeholder="请选择是否外派" />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="2" header="调岗信息">
            <a-row :gutter="48">
              <a-col :span="8">
                <a-form-model-item label="调整前部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="beforeDepartId">
                  <j-select-depart v-model="model.beforeDepartId" disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="调整前岗位序列" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="beforePositionCategory">
                  <j-dict-select-tag
                    type="list"
                    v-model="model.beforePositionCategory"
                    dictCode="position_category"
                    placeholder="请选择调整前岗位序列"
                    disabled
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="调整前职务级别" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="beforePositionLevelId">
                  <j-dict-select-tag
                    type="list"
                    v-model="model.beforePositionLevelId"
                    dictCode="erp_org_position_level,level_name,id,del_flag='0' and audit_status='2'"
                    placeholder="请选择调整前职务级别"
                    disabled
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="调整前岗位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="beforePostId">
                  <j-search-select
                    v-model="model.beforePostId"
                    dict="sys_position,name,id,del_flag = 0 and audit_status=2"
                    placeholder="请选择调整前岗位"
                    disabled
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="调整前所属团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="beforeTeamId">
                  <select-team-input v-model="model.beforeTeamId" :tdlx="3" disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="调整前薪级" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="beforeSalaryScale">
                  <j-dict-select-tag
                    type="list"
                    v-model="model.beforeSalaryScale"
                    dictCode="erp_pay_grade,salary_grade,id,del_flag = 0 and audit_status=2 order by sort"
                    placeholder="请选择调整前薪级"
                    disabled
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="调整前车贴(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="beforeVehicleSubsidies">
                  <a-input-number
                    :max="999999999"
                    :min="0"
                    :precision="2"
                    v-model="model.beforeVehicleSubsidies"
                    placeholder="请输入调整前车贴(元)"
                    style="width: 100%"
                    disabled/>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="48">
              <a-col :span="8">
                <a-form-model-item label="调整后部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="afterDepartId">
                  <j-select-depart :disabled="formDisabled" v-model="model.afterDepartId" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="调整后岗位序列" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="afterPositionCategory">
                  <j-dict-select-tag
                    :disabled="formDisabled"
                    type="list"
                    v-model="model.afterPositionCategory"
                    dictCode="position_category"
                    placeholder="请选择调整后岗位序列"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="调整后职务级别" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="afterPositionLevelId">
                  <j-dict-select-tag
                    :disabled="formDisabled"
                    type="list"
                    v-model="model.afterPositionLevelId"
                    :dictCode="positionLevelIdDict"
                    placeholder="请选择调整后职务级别"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="调整后岗位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="afterPostId">
                  <j-search-select
                    :disabled="formDisabled"
                    v-model="model.afterPostId"
                    :dict="positionIdDict"
                    placeholder="请选择调整后岗位"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="调整后所属团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="afterTeamId">
                  <select-team-input :disabled="formDisabled" v-model="model.afterTeamId" :tdlx="3" queryType="parent" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="调整后薪级" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="afterSalaryScale">
                  <j-dict-select-tag
                    :disabled="formDisabled"
                    type="list"
                    v-model="model.afterSalaryScale"
                    dictCode="erp_pay_grade,salary_grade,id,del_flag = 0 and audit_status=2 order by sort"
                    placeholder="请选择调整后薪级"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="调整后车贴(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="afterVehicleSubsidies">
                  <a-input-number
                    :disabled="formDisabled"
                    :max="999999999"
                    :min="0"
                    :precision="2"
                    v-model="model.afterVehicleSubsidies"
                    placeholder="请输入调整后车贴(元)"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="调整原因" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="adjustReason">
                  <a-textarea :disabled="formDisabled" v-model="model.adjustReason" rows="4" :max-length="500" placeholder="请输入调整原因" />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="3" header="交接信息">
            <a-row :gutter="48">
              <a-col :span="12">
                <a-form-model-item label="工作交接" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isWorkHandover">
                  <j-dict-select-tag
                    :disabled="formDisabled"
                    type="radio"
                    v-model="model.isWorkHandover"
                    dictCode="yes_or_no"
                    placeholder="请选择工作交接"
                    @input="selectIsWorkHandover"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="12" v-if="model.isWorkHandover=='1'">
                <a-form-model-item label="交接人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="workHandoverPerson">
                  <select-user-by-dep :multi="false" :disabled="formDisabled" v-model="model.workHandoverPerson" ></select-user-by-dep>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="48">
              <a-col :span="12">
                <a-form-model-item label="办公设备交接情况" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isOfficeSupplies">
                  <j-dict-select-tag
                    :disabled="formDisabled"
                    type="radio"
                    v-model="model.isOfficeSupplies"
                    dictCode="yes_or_no"
                    placeholder="请选择办公设备交接情况"
                    @input="selectIsOfficeSupplies"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="12" v-if="model.isOfficeSupplies=='1'">
                <a-form-model-item label="接收人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="officeSuppliesPerson">
                  <select-user-by-dep :multi="false" :disabled="formDisabled" v-model="model.officeSuppliesPerson" ></select-user-by-dep>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="48">
              <a-col :span="12">
                <a-form-model-item label="有无借款" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isLoan">
                  <j-dict-select-tag
                    :disabled="formDisabled"
                    type="radio"
                    v-model="model.isLoan"
                    dictCode="yes_or_no"
                    placeholder="请选择有无借款"
                    @input="selectIsLoan"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="12" v-if="model.isLoan=='1'">
                <a-form-model-item label="借款金额(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="loanMoney">
                  <a-input-number
                    :disabled="formDisabled"
                    :max="999999999"
                    :min="0"
                    :precision="2"
                    v-model="model.loanMoney"
                    placeholder="请输入借款金额(元)"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="4" header="附件信息">
            <a-row :gutter="48">
              <a-col :span="12">
                <a-form-model-item label="附件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attachment">
                  <j-upload :disabled="formDisabled" v-model="model.attachment" ></j-upload>
                </a-form-model-item>
              </a-col>
            <!-- <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
              <a-button @click="submitForm">提 交</a-button>
            </a-col> -->
            </a-row>
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
    </j-form-container>

    <a-row type="flex" justify="center">
      <a-col :span="24">
        <!-- 流程历史跟踪 -->
        <common-flow-list v-if="formBpm && model.bpmStatus !== '1'" :formData="formData"></common-flow-list>
      </a-col>
      <a-col :span="24" style="text-align: center;margin-top: 15px">
        <a-button type="primary" v-if="formBpm" :style="{ marginRight: showFlowSubmitButton?'10px':'0px' }" @click="onPrint">打印</a-button>
        <a-button @click="submitForm('submit')" v-if="showFlowSubmitButton">提 交</a-button>
      </a-col>
    </a-row>
    <process-config-modal ref="processConfig" @ok="handleSuccess" @close="handleClose"></process-config-modal>
    <ErpHrEmployeeAdjustPostBillFormPrint id="printContent" class="print_style" :formData="model" :formDataHistory="formData || {}"></ErpHrEmployeeAdjustPostBillFormPrint>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
  import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
  import JSearchSelect from '@/views/scy/components/JSearchSelect.vue'
  import ProcessConfigModal from '@/views/scy/components/ProcessConfigModal'
  import CommonFlowList from '@/views/components/CommonFlowList.vue' // 审批历史流程列表组件
  import ErpHrEmployeeAdjustPostBillFormPrint from './ErpHrEmployeeAdjustPostBillFormPrint.vue'
  import moment from 'moment'
  import { mapGetters } from 'vuex'
  import Print from '@/utils/print/printarea.js';

  export default {
    name: 'ErpHrEmployeeAdjustPostBillForm',
    components: {
      SelectUserByDep,
      SelectTeamInput,
      JSearchSelect,
      ProcessConfigModal,
      CommonFlowList,
      ErpHrEmployeeAdjustPostBillFormPrint
    },
    props: {
      // 流程表单data
      formData: {
        type: Object,
        default: () => {},
        required: false
      },
      // 表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        activeKey: ['1', '2', '3', '4'],
        model: {},
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 }
        },
        confirmLoading: false,
        positionIdDict: 'sys_position,name,id,del_flag = 0 and audit_status=2 and is_virtual=0',
      positionLevelIdDict: 'erp_org_position_level,level_name,id,del_flag="0" and audit_status="2"',
        validatorRules: {
          arrivalTime: [
              { required: true, message: '请选择预计到岗时间!' }
          ],
          isExpatriate: [
              { required: true, message: '请选择是否外派!' }
          ],
          afterDepartId: [
              { required: true, message: '请选择调整后部门!' }
          ],
          afterPositionCategory: [
              { required: true, message: '请选择调整后岗位序列!' }
          ],
          afterPositionLevelId: [
              { required: true, message: '请选择调整后职务级别!' }
          ],
          afterPostId: [
              { required: true, message: '请选择调整后岗位!' }
          ],
          afterTeamId: [
              { required: true, message: '请选择调整后所属团队!' }
          ],
          afterSalaryScale: [
              { required: true, message: '请选择调整后薪级!' }
          ],
          afterVehicleSubsidies: [
              { required: true, message: '请输入调整后车贴(元)!' },
              { pattern: /^[0-9]*[1-9][0-9]*|0$/, message: '请输入正整数!' }
          ],
          adjustReason: [
              { required: true, message: '请输入调整原因!' }
          ],
          isWorkHandover: [
              { required: true, message: '请选择工作交接!' }
          ],
          workHandoverPerson: [
              { required: true, message: '请选择交接人!' }
          ],
          isOfficeSupplies: [
              { required: true, message: '请选择办公设备交接情况!' }
          ],
          officeSuppliesPerson: [
              { required: true, message: '请选择接收人!' }
          ],
          isLoan: [
              { required: true, message: '请选择有无借款!' }
          ],
          loanMoney: [
              { required: true, message: '请输入借款金额(元)!' },
              { pattern: /^[0-9]*[1-9][0-9]*|0$/, message: '请输入正整数!' }
          ]
        },
        url: {
          startProcess: '/api/erpmng/act/process/extActProcess/startMutilProcess',
          getBillNo: '/api/erp/hr/adjust/erpHrEmployeeAdjustPostBill/getBillNo',
          add: '/api/erp/hr/adjust/erpHrEmployeeAdjustPostBill/add',
          edit: '/api/erp/hr/adjust/erpHrEmployeeAdjustPostBill/edit',
          queryById: '/api/erp/hr/adjust/erpHrEmployeeAdjustPostBill/queryById',
          queryPostRecordByInfo: '/api/erp/files/employee/erpEmployeePostChangeRecord/queryPostRecordByInfo',
          queryFileById: '/api/erp/files/employee/erpEmployeeFile/queryFileById'
        },
        // 代码生成后需手动设置流程编码
        flowCode: 'onl_erp_hr_employee_adjust_post_bill',
        formUrl: 'erp/hr/adjust/modules/ErpHrEmployeeAdjustPostBillForm',
        formUrlMobile: '/pages/synergy/erpHrEmployeeAdjustPostBillForm',
        beanName: 'erpHrEmployeeAdjustPostBillServiceImpl'
      }
    },
    computed: {
      formDisabled() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return true
          }
        }
        return false
      }
    },
    created () {
       // 备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      // 如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
    },
    methods: {
      selectIsWorkHandover(data) {
        if (data == '0') {
          this.$set(this.model, 'workHandoverPerson', null);
        }
      },
      selectIsOfficeSupplies(data) {
        if (data == '0') {
          this.$set(this.model, 'officeSuppliesPerson', null);
        }
      },
      selectIsLoan(data) {
        if (data == '0') {
          this.$set(this.model, 'loanMoney', null);
        }
      },
      // 获取编号
      getBillNo() {
        getAction(this.url.getBillNo, {}).then((res) => {
          if (res.success) {
            let data = res.result.records || res.result
            this.$set(this.model, 'billNo', data)
          }
        })
      },
      ...mapGetters(['userInfo']),
      add () {
        this.edit(this.modelDefault);
        this.getBillNo();
        this.model.employeeId = this.userInfo().empId;
        this.model.applyId = this.userInfo().employee.applyId;
        this.model.beforeDepartId = this.userInfo().deptId;
        this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
        this.$set(this.model, 'bpmBizTitle', '人员调岗单' + '-' + this.userInfo().realname + '-' + moment().format('YYYY年MM月DD日'));
        getAction(this.url.queryPostRecordByInfo, { employeeId: this.userInfo().empId, departId: this.userInfo().deptId }).then(res => {
          if (res.success) {
            let data = res.result;
            if (data) {
              this.$set(this.model, 'beforeTeamId', data[0].teamId);
              this.$set(this.model, 'beforePostId', data[0].postId);
              this.$set(this.model, 'beforePositionCategory', data[0].positionCategory);
              this.$set(this.model, 'beforePositionLevelId', data[0].positionLevelId);
            } else {
              this.$message.warning('未找到当前部门对应的岗位信息，请切换部门重新选择！');
            }
          }
        })
        getAction(this.url.queryFileById, { id: this.userInfo().empId }).then(res => {
          if (res.success) {
            let data = res.result;
            if (data) {
              this.$set(this.model, 'beforeSalaryScale', data.payGradeId);
              this.$set(this.model, 'beforeVehicleSubsidies', data.carSubsidy);
            }
          }
        })
      },
      edit (record) {
        this.$refs.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;
      },
      // 渲染流程表单数据
      showFlowData() {
        if (this.formBpm === true) {
          let params = { id: this.formData.dataId };
          getAction(this.url.queryById, params).then((res) => {
            if (res.success) {
              this.edit(res.result);
            }
          });
        }
      },
      // 发起流程
    startProcess: function (id) {
        let record = { id: id };
        this.$refs.processConfig.visible = true
        this.$refs.processConfig.formUrl = this.formUrl
        this.$refs.processConfig.formUrlMobile = this.formUrlMobile
        this.$refs.processConfig.flowCode = this.flowCode
        this.$refs.processConfig.edit(record, '', this.beanName);
    },
    // 保存草稿
    submitTempForm() {
      const that = this
      // 触发表单验证
      // that.confirmLoading = true
      let httpurl = ''
      let method = ''
      if (!this.model.id) {
        httpurl += this.url.add
        method = 'post'
      } else {
        httpurl += this.url.edit
        method = 'put'
      }
      httpAction(httpurl, this.model, method)
        .then((res) => {
          if (res.success) {
            that.$message.success(res.message)
            that.$emit('ok', 'draft', this.model);
          } else {
            that.$message.warning(res.message)
            that.unButtonDisable()
          }
        }).catch(err => {
          that.unButtonDisable(err)
        })
        .finally(() => {
          // that.confirmLoading = false
        })
    },
    handleSuccess() {
      this.$emit('ok', 'refresh');
    },
    handleClose () {
      this.$emit('close');
    },
    submitForm (type) {
      const that = this;
      if (type && type == 'draft') {
        this.submitTempForm()
        return false
      }
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true;
          let httpurl = '';
          let method = '';
          if (!this.model.id) {
            httpurl += this.url.add;
            method = 'post';
          } else {
            httpurl += this.url.edit;
            method = 'put';
          }
          httpAction(httpurl, this.model, method).then((res) => {
            // if(res.success){
            //   that.$message.success(res.message);
            //   that.$emit('ok');
            // }else{
            //   that.$message.warning(res.message);
            //   that.$emit('unButtonDisable');
            // }
            if (res.success) {
              let data = res.result;
              if (this.model.id) {
                this.startProcess(this.model.id);
              } else {
                this.startProcess(data);
              }
            } else {
              that.$emit('unButtonDisable');
              that.$message.warning(res.message)
            }
          }).catch((error) => {
            that.$emit('unButtonDisable', error);
          }).finally(() => {
            that.confirmLoading = false;
          })
        } else {
        that.$emit('unButtonDisable');
        }
      })
    },

    // 点击打印
    onPrint () {
      let print = new Print({
        el: '#printContent',
        popTitle: '人员调岗单详情 · 禾美环保',
        endCallback() {

        }
      })
    }
    }
  }
</script>
